package com.ceadeal.admin.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 功能描述: 线程
 *
 * 作者: Yzw
 * 日期: 2017-03-09 19:46:43
 */
@Service
public class ExecutorService implements InitializingBean, DisposableBean {

    private static Logger log = LoggerFactory.getLogger(ExecutorService.class);

    private ThreadPoolExecutor poolExecutor;

    public void executeCommand(Runnable command) {
        poolExecutor.execute(new ExecutorRunnable(command));
    }

    @Override
    public void destroy() throws Exception {
        poolExecutor.shutdown();
        poolExecutor.awaitTermination(10, TimeUnit.SECONDS);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        int corePoolSize = Runtime.getRuntime().availableProcessors() + 1;
        int maximumPoolSize = corePoolSize * 2;
        poolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
        poolExecutor.allowCoreThreadTimeOut(true);
    }

    public class ExecutorRunnable implements Runnable {

        private Runnable command;

        ExecutorRunnable(Runnable command) {
            this.command = command;
        }

        @Override
        public void run() {
            try {
                command.run();
            } catch (Throwable t) {
                log.error(t.getMessage());
            }
        }
    }
}
